<template>
  <div id="area" >
    <searchTablePagination
      ref="searchtable"
      :searchFormData="searchFormData"
      :has-form="tableConfig.hasForm"
      :loading="tableLoading"
      :table-config="tableConfig"
      @pieOp="pieOp"
      @ec="ec"
      @handleSelectionChange="handleSelectionChange"
    >
      <template>
        <el-form :model="searchFormData"  label-width="90px" ref="ruleForm">

          <el-row>

            <el-col :span="6">
              <el-form-item label="类型：" prop="theme">
                <el-input disabled v-model="searchFormData.theme" style="width: 80%" clearable placeholder="类型" size="mini"/>
              </el-form-item>
            </el-col>
          </el-row>

        </el-form>
      </template>

      <template>
         <div slot="leftTableExtraOperate">
           <div style="font-size: 13px;color: #20a0ff">平台： {{searchFormData.platformName }}  |  系统ID：  {{sid}}  | 系统名称： {{sname}} </div>
         </div>
        <div slot="rightTableExtraOperate">
             <el-button type="primary" @click="$router.back()">返回</el-button>
        </div>

      </template>
      <template slot="expand" slot-scope="scope">
        <div style="margin-left: 5rem;width: 95%;display: flex">
          <div style="width: 73%;">
            <el-descriptions class="margin-top" :column="2" size="small" border>
        <!--      <el-descriptions-item v-if="scope.row.hasOwnProperty('reportId')">
                <template slot="label">
                  报告ID
                </template>
                {{ scope.row.reportId }}
              </el-descriptions-item>

              <el-descriptions-item v-if="scope.row.hasOwnProperty('projectId')">
                <template slot="label">
                  项目ID
                </template>
                {{ scope.row.projectId}}
              </el-descriptions-item>-->

              <el-descriptions-item v-if="searchFormData.platformName=='MeterSphere'">
                <template slot="label">
                  工作空间名称
                </template>
                {{ $route.query.workspaceName}}
              </el-descriptions-item>
          <!--    <el-descriptions-item v-if="scope.row.hasOwnProperty('workspaceId')">
                <template slot="label">
                  工作空间ID
                </template>
                {{ scope.row.workspaceId}}
              </el-descriptions-item>-->

              <el-descriptions-item v-if="scope.row.hasOwnProperty('testPlanName')">
                <template slot="label">
                  测试计划名称
                </template>
                {{ scope.row.testPlanName}}
              </el-descriptions-item>
              <el-descriptions-item v-if="searchFormData.platformName=='MeterSphere'">
                <template slot="label">
                  项目名称
                </template>
                {{ $route.query.projectName}}
              </el-descriptions-item>
              <el-descriptions-item v-if="scope.row.hasOwnProperty('platformName')">
                <template slot="label">
                  报告平台名称
                </template>
                {{ scope.row.platformName}}
              </el-descriptions-item>

              <el-descriptions-item v-if="scope.row.hasOwnProperty('creator')">
                <template slot="label">
                  计划创建者
                </template>
                {{ scope.row.creator}}
              </el-descriptions-item>

              <el-descriptions-item v-if="scope.row.hasOwnProperty('status')">
                <template slot="label">
                  执行结果
                </template>
                <el-tag> {{ scope.row.status}} </el-tag>
              </el-descriptions-item>
              <el-descriptions-item v-if="scope.row.hasOwnProperty('costTime')">
                <template slot="label">
                  执行时长（毫秒）
                </template>

                <el-tag>{{ scope.row.costTime}}</el-tag>
              </el-descriptions-item>

              <el-descriptions-item v-if="scope.row.hasOwnProperty('caseCount')">
                <template slot="label">
                  用例个数
                </template>
                <el-tag>{{ scope.row.caseCount}}</el-tag>
              </el-descriptions-item>

              <el-descriptions-item v-if="scope.row.hasOwnProperty('passCount')">
                <template slot="label">
                  成功个数
                </template>
                {{ scope.row.passCount}}
              </el-descriptions-item >

              <el-descriptions-item v-if="scope.row.hasOwnProperty('failedCount')">
                <template slot="label">
                  失败数
                </template>
                {{ scope.row.failedCount}}
              </el-descriptions-item>

              <el-descriptions-item v-if="scope.row.hasOwnProperty('brokenCount')">
                <template slot="label">
                  用例异常个数
                </template>
                {{ scope.row.brokenCount}}
              </el-descriptions-item>

              <el-descriptions-item v-if="scope.row.hasOwnProperty('skippedCount')">
                <template slot="label">
                  未执行用例个数
                </template>
                {{ scope.row.skippedCount}}
              </el-descriptions-item>

              <el-descriptions-item v-if="scope.row.hasOwnProperty('unknownCount')">
                <template slot="label">
                  未知原因识别个数
                </template>
                {{ scope.row.unknownCount}}
              </el-descriptions-item>


              <el-descriptions-item v-if="scope.row.hasOwnProperty('executeCount')">
                <template slot="label">
                  执行个数
                </template>
                {{ scope.row.executeCount}}
              </el-descriptions-item>


              <el-descriptions-item v-if="scope.row.hasOwnProperty('executeRate')">
                <template slot="label">
                  执行率
                </template>
                {{ scope.row.executeRate}}
              </el-descriptions-item>
              <el-descriptions-item v-if="scope.row.hasOwnProperty('triggerMode')">
                <template slot="label">
                  执行方式
                </template>
                {{ scope.row.triggerMode}}
              </el-descriptions-item>

              <el-descriptions-item v-if="scope.row.hasOwnProperty('runMode')">
                <template slot="label">
                  触发方式
                </template>
                {{ scope.row.runMode}}
              </el-descriptions-item>
              <el-descriptions-item v-if="scope.row.hasOwnProperty('projectEnvMap')">
                <template slot="label">
                  MS执行环境
                </template>
                {{ scope.row.projectEnvMap}}
              </el-descriptions-item>
              <el-descriptions-item v-if="scope.row.hasOwnProperty('apiScenarioResult')">
                <template slot="label">
                  场景执行概况
                </template>
                {{ scope.row.apiScenarioResult}}
              </el-descriptions-item>
              <el-descriptions-item v-if="scope.row.hasOwnProperty('insertTime')">
                <template slot="label">
                  入库时间
                </template>
                {{ scope.row.insertTime}}
              </el-descriptions-item>
            </el-descriptions>
          </div>
          <div class="piechart">
            <div style="width: 18rem;height: 15rem">
              <div :id="'pieChart_' + scope.row.id" class="echart" style="width: 18rem;height: 15rem"></div>
            </div>
          </div>
        </div>
      </template>
    <!--  <template slot="id" slot-scope="scope">
        <div style="display: flex">
          <div style="margin-left: 10px;" v-if="scope.row.platformName=='Pytest'">
            <el-tag  style="background-color:sandybrown;">P</el-tag>
          </div>
          <div  style="margin-left: 10px;" v-if="scope.row.platformName=='MeterSphere'">
            <el-tag >M</el-tag>
          </div>
        </div>
      </template>-->

      <template slot="tableOperator" slot-scope="scope">
        <!--    <div style="display: flex;justify-content: center">
              <el-button type="primary" @click="editData(scope.row)"  v-permission="{action:'updDemand'}">修改</el-button>
              <el-button type="danger"  @click="deletes(scope.row.resourceID)"  v-permission="{action:'delDemand'}">删除</el-button>
            </div>-->

        <div style="display: flex;justify-content: center;align-items: center">
          <el-button size="mini" @click="reportDetail(scope.row)"> 报告详情</el-button>
<!--          <el-button  type="primary" size="mini" @click="toHT(scope.row)"> 历史执行记录</el-button>-->
        </div>

      </template>

    </searchTablePagination>
  </div>
</template>

<script>
  import * as echarts from "echarts";
  import searchTablePagination from "./searchTable/searchTablePagination"

  import domain from '../../../domain.js'


  const base = domain.target

  export default {
    name: 'DemandManagement',
    components: {
      searchTablePagination,

    },
    created () {
      this.searchFormData.platformName = this.$route.query.platformName
      this.searchFormData.testPlanName = this.$route.query.testPlanName
      this.sid = this.$route.query.sid
      this.sname = this.$route.query.sname
      console.log("this.searchFormData",this.searchFormData)
      this.$nextTick(()=>{
        console.log(document.querySelector("#area").clientHeight)
        let H = document.querySelector("#area").clientHeight
        if (H>300){
          this.tableConfig.tableHeight = H+320
        }else{
          this.tableConfig.tableHeight = H+220
        }
      })
      // this.searchDemandStatusList()
    },
    mounted() {
      this.userInfo = JSON.parse(localStorage.getItem("userInfo")) ||{}
    },
    activated() {
      console.log("activated")
    },
    data () {
      return {
        sid:"",
        sname:"",
        userInfo:null,
        sourceList:[
          {
            textName:"local",
            value:"local"
          },
          {
            textName:"PMS",
            value:"PMS"
          },
          {
            textName:"ZenTao",
            value:"ZenTao"
          },
        ],
        selectedRows:[],
        taskModalVisible:false,
        ImportDemandModalVisible:false,
        dialogTitle:"新增",
        rowData:{},// 需求对象数据
        tableLoading:false,
        tableData:[],
        statusList:[],
        searchFormData: {
          platformName:"",
          testPlanName:""
        },

        tableConfig: {
          tableHeight:0,
          // requestUrl:`${base}/basic/user/findByNameAndNumberAndName`,
          requestUrl:`${base}/join/reports/history`,
          hasForm:true,
          isRadio: false,
          topOperate: true,
          isIndex:true,
          columnConfig: [
            { isSlot:true,expand:true,fixed:"left"},
            // { prop: 'id', label: '平台类型',width:100, isSlot: "id"},
            { prop: 'reportName', label: '报告名称' },
            { prop: 'passRate', label: '通过率',width:150, },
            { prop: 'createTime', label: '测试计划创建时间' },
            { prop: 'endTime', label: '测试计划结束时间' },
            { prop:"operator",label:"操作",width:150} // fixed:"right",
          ]
        },
      }
    },
    methods: {

      renderPieChart(pass, containerId) {
        let fail;
        if (pass ==0){
          fail=1
        }else{
          pass = parseFloat(pass) / 100;
          fail = (1-pass).toFixed(2)
        }
        let dataArr = [
          {
            value:pass,
            name:"通过率",
            itemStyle: { color: '#67c23a' }
          },
          {
            value:fail,
            name:"失败率",
            itemStyle: { color: 'red' }
          }
        ]
        const chart = echarts.init(document.getElementById(containerId));
        console.log("chart",chart)
        console.log("dataArr",dataArr);
        if (chart){
          const option = {
            title: {
              text: '通过率/失败率',
              // subtext: 'Fake Data',
              left: 'center',
              textStyle:{
                fontStyle:"normal",
                fontSize:"14",
              },
            },
            label: {
              show: true,
              position: 'top',
              // color: 'rgba(119,167,255,1)',
              fontSize: 12,
              textAlign: 'center',
            },
            tooltip: {
              trigger: 'item',
              formatter:function(params){
                // console.log("params",params)
                return `${params.name}为${params.value*100}% `
              },
              textStyle: {
                color: "rgba(212, 232, 254, 1)",
                // fontSize: fontChart(0.24),
              },
            },
            /*   legend: {
                 orient: 'vertical',
                 left:"left",
                 bottom: 'top',

               },*/
            series: [
              {
                name: '通过率',
                type: 'pie',
                radius: '50%',
                data:dataArr,
                emphasis: {
                  itemStyle: {
                    shadowBlur: 10,
                    shadowOffsetX: 0,
                    shadowColor: 'rgba(0, 0, 0, 0.5)'
                  }
                }
              }
            ]
          }
          chart.setOption(option);
        }

      },

      reportDetail(row){

        if (this.searchFormData.platformName == "MeterSphere"){
          let resultArr = JSON.parse(row.apiScenarioResult)
          let errorCount = 0
          let successCount = 0
          let pendingCount = 0
          let stoppedCount = 0
          resultArr.forEach((item)=>{
            if (item.status=="ERROR"){
              errorCount = item.count
            }
            if (item.status=="SUCCESS"){
              successCount = item.count
            }

            if (item.status=="PENDING"){
              pendingCount = item.count
            }

            if (item.status=="STOPPED"){
              stoppedCount = item.count
            }

          })
          this.$router.push({
            path:"/msdetail",
            query:{
              reportId:row.reportId,
              reportName:row.reportName,
              successCount,
              errorCount,
              pendingCount,
              stoppedCount,
            }
          })
        }

        if (this.searchFormData.platformName == 'Pytest'){
          this.$router.push({
            path:"/pydetail",
            query:{
              reportId:row.reportId,
              reportName:row.reportName,
              brokenCount:row.brokenCount,
              failedCount:row.failedCount,
              skippedCount:row.skippedCount,
              passCount:row.passCount,
              unknownCount:row.unknownCount,

            }
          })
        }

      },

      toHT(row){
        // testPlanName=&platformType= &page=&pageSize=
        this.$router.push({
          path:"/historyTable",
          query:{
            testPlanName: row.testPlanName,
            platformName: row.platformName,
          }
        })
      },

      getTemplateRow(val){

      },
      handleSelectionChange(rows){
        console.log("选中的数据",rows)
        this.selectedRows = rows
      },
      pieOp(data){

        // data.forEach((row, index) => {
        //   console.log("row",row)
        //   this.renderPieChart(row.passRate, 'pieChart_' + row.id);
        //   // this.renderPieChart(row.passRate, 'pieChart' );
        // },3000);
      },
      ec(row,rows){
        // console.log(row,rows)
        this.$nextTick(()=>{
          this.renderPieChart(row.passRate, 'pieChart_'+ row.id );

        })
      },

      chakan(row){
        console.log(row)
        this.$router.push({
          path:"/process",
          query:{
            row
          }
        })
      }
    },

    computed: {
      /*  testSystemList(){
          return this.$store.getters.chosenSystemList
        },
        systemID(){
          return this.$store.getters.activeSystem
        }*/
    },
    watch: {
      /*    systemID:{
            immediate:true,
            handler(newVal,oldVal){
              this.searchFormData.sid = newVal
              setTimeout(()=>{
                this.$refs.searchtable.handleSearch() //
              })
            }
          }*/
    },
  }

</script>

<style scoped lang="scss">
  #area{

  }
  .demo-table-expand {
    /*font-size: 0;*/
  }
  .demo-table-expand label {
    width: 120px;
    color: #99a9bf;
  }
  .demo-table-expand .el-form-item {

    width: 40%;
  }

  ::v-deep .el-descriptions-item__label.is-bordered-label{
    width: 160px;
  }
  .piechart{
    flex:1;
    margin-left: 10px;
    border: 1px solid #e8e8e8;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: #e8e8e8;
  }
</style>
